package com.yiren.backstage.currency.utils;

import static com.yiren.backstage.currency.constant.DbConstant.USER_DATA_URL;

import android.content.Context;
import android.os.Environment;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static String[] fetchAvailableDataArray() {
        File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/yirenv3/dbaf/data/");
        File[] files = root.listFiles();
        List<String> filePathList = new ArrayList<String>();
        for (File file : files) {
            String fileName = file.getName();
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (file.isFile() && "db".equals(prefix)) {
                filePathList.add(fileName);
            }
        }
        String[] dataArray = new String[filePathList.size()];
        return filePathList.toArray(dataArray);
    }

    /***
     * 获取sdcard 可用目录,某些安卓系统挂载sdcard时存在sdcard1、sdcard2、sdcard3
     */
    public static String fetchAvailableSdcardFoloder() {
        String base = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dataPath = USER_DATA_URL;
        File data = new File(base + dataPath);
        if (null != data && !data.exists()) {
            for (int i = 0; i < 5; i++) {
                String findBase = base + i;
                File findData = new File(findBase + dataPath);
                if (findData.exists()) {
                    return findBase;
                }
            }
        }
        return base;
    }

    /**
     * 删除当前目录所有文件
     *
     * @param path
     */
    public static void deleteAll(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (file.isFile() || file.listFiles().length == 0) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteAll(f.getAbsolutePath());
                f.delete();
            }
            file.delete();
        }
    }

    /**
     * 删除当前目录所有文件
     *
     * @param path
     */
    public static boolean deleteFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return true;
        }
        if (file.isFile() || file.listFiles().length == 0) {
            return file.delete();
        } else {
            File[] files = file.listFiles();
            for (File f : files) {
                deleteAll(f.getAbsolutePath());
                return f.delete();
            }
        }
        return false;
    }

    /**
     * 根据路径创建文件夹
     *
     * @param folderPath
     */
    public static File createFolder(String folderPath) {
        //创建文件夹
        File destDir = new File(folderPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        return destDir;
    }

    /**
     * 根据路径创建文件夹
     */
    public static File createFile(String name) {
        File file = new File(name);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();//创建目录
            }
            try {
                file.createNewFile();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        return file;
    }

    /**
     * 将byte数组写入到磁盘文件
     *
     * @param b
     * @param path
     * @throws Exception
     */
    public static void saveFile(byte[] b, String path) throws Exception {
        if (b == null) return;
        File file = new File(path);
        FileOutputStream fis = null;
        BufferedOutputStream bos = null;
        try {
            fis = new FileOutputStream(file);
            bos = new BufferedOutputStream(fis);
            bos.write(b);
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            if (bos != null) {
                bos.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }

    /**
     * 判断文件是否存在
     */
    public static boolean exists(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    /**
     * @param path
     * @throws InterruptedException
     */
    public boolean isExitsPath(String path) throws InterruptedException {
        String[] paths = path.split("\\");
        StringBuffer fullPath = new StringBuffer();
        for (int i = 0; i < paths.length; i++) {
            fullPath.append(paths[i]).append("\\");
            File file = new File(fullPath.toString());
            if (paths.length - 1 != i) {// 判断path到文件名时，无须继续创建文件夹！
                if (!file.exists()) {
                    file.mkdir();
                    System.out.println("创建目录为：" + fullPath.toString());
                }
            }
        }
        File file = new File(fullPath.toString());// 目录全路径
        if (!file.exists()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isExist(String filePath) {
        String paths[] = filePath.split("\\");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 2; i++) {// 注意此处循环的长度
            try {
                dir = dir + "/" + paths[i + 1];
                File dirFile = new File(dir);
                if (!dirFile.exists()) {
                    dirFile.mkdir();
                    System.out.println("创建目录为：" + dir);
                }
            } catch (Exception err) {
                System.err.println("ELS - Chart : 文件夹创建发生异常");
            }
        }
        File fp = new File(filePath);
        if (!fp.exists()) {
            return true; // 文件不存在，执行下载功能
        } else {
            return false; // 文件存在不做处理
        }
    }

    /**
     * 将字节转换成M
     *
     * @param bytes
     */
    public static String byteToMegaBate(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP).floatValue();
        return returnValue + "MB";
    }

    /**
     * 判断文件是否存在并获取文件大小
     *
     * @return
     */
    public static String getFileLength(File file) {
        if (file.exists() && file.isFile()) {
            return byteToMegaBate(file.length());
        } else {
            return "0.00MB";
        }
    }

    /**
     * 判断文件是否存在并获取文件大小
     *
     * @return
     */
    public static String getFileSizeToMb(File file) {
        if (file.exists()) {
            return byteToMegaBate(getFileSize(file));
        } else {
            return "0.00MB";
        }
    }

    /**
     * 获取文件或文件夹大小
     *
     * @param f
     */
    public static long getFileSize(File f) {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    /***
     * 根据文件/文件夹 返回 文件名/文件夹名
     *
     * @param file 文件/文件夹
     * @return 文件名/文件夹名
     */
    public static String getFileName(File file) {
        if (file.isFile()) {
            file.getName();
        }
        if (file.isDirectory()) {
            StringBuffer sb = new StringBuffer(file.getPath());
            return sb.substring(sb.lastIndexOf("\\") + 1, sb.length());
        }
        return "";
    }

    /***
     * 根据文件/文件夹 返回 文件名/文件夹名
     *
     * @param file 文件/文件夹
     * @return 文件名/文件夹名
     */
    public static String getDirectoryFile(File file) {
        if (file.isFile()) {
            file.getName();
        }
        if (file.isDirectory()) {
            StringBuffer sb = new StringBuffer(file.getPath());
            return sb.substring(sb.lastIndexOf("\\") + 1, sb.length());
        }
        return "";
    }

    /***
     * 根据文件/文件夹 返回 文件名/文件夹名
     *
     * @param file 文件/文件夹
     * @return 文件名/文件夹名
     */
    public static String getFileNameDtpId(File file) {
        if (file.isFile()) {
            StringBuffer sb = new StringBuffer(file.getName());
            return sb.substring(3, sb.lastIndexOf("."));
        }
        if (file.isDirectory()) {
            StringBuffer sb = new StringBuffer(file.getPath());
            return sb.substring(sb.lastIndexOf("\\") + 1, sb.length());
        }
        return "";
    }

    /***
     * 根据文件/文件夹 返回文件名
     *
     * @return 文件名/文件夹名
     */
    public static String getDistrictId(String filename) {
        File file = new File(filename);
        if (file.isFile()) {
            StringBuffer sb = new StringBuffer(file.getName());
            return sb.substring(3, sb.lastIndexOf("."));
        }
        return "";
    }

    /***
     * 根据全国文件夹 返回区划ID
     * @return 文件名/文件夹名
     */
    public static List<Integer> getFileNameList(String filename) {
        List<Integer> filenameList = new ArrayList<Integer>();
        File file = new File(filename);
        String[] dataList = file.list();
        for (String s : dataList) {
            String name = getDistrictId(filename + "\\" + s);
            if (!StringUtil.isEmpty(name)) {
                filenameList.add(Integer.valueOf(name));
            }
        }
        return filenameList;
    }

    /***
     * 根据全国文件夹 返回区划ID
     * @return 文件名/文件夹名
     */
    public static List<Integer> getDistrictList(String filename) {
        List<Integer> filenameList = new ArrayList<Integer>();
        File file = new File(filename);
        String[] datalist = file.list();
        for (String s : datalist) {
            filenameList.add(Integer.valueOf(s));
            String name = filename + File.separator + s;
            File child = new File(name);
            String[] childlist = child.list();
            for (String c : childlist) {
                filenameList.add(Integer.valueOf(c));
            }
        }
        return filenameList;
    }

    // /***
    // * 根据全国数据下载文件夹 返回数据下载信息列表
    // *
    // * @param file文件/文件夹
    // * @return 数据下载信息列表
    // */
    // public static List<DownloadModel> getDownloadModelByFileName(String
    // filename) {
    // List<DownloadModel> downloadDataInfos = new ArrayList<DownloadModel>();
    // File file = new File(filename);
    // String[] datalist = file.list();
    // for(String s:datalist){
    // String districtId = getDistrictId(filename+"\\"+s);
    // if(!StringUtil.isEmpty(districtId)){
    // DownloadModel downloadDataInfo = new DownloadModel();
    // downloadDataInfo.setDownloadDistrict(Integer.valueOf(districtId));
    // // district.setId(Integer.valueOf(name));
    // downloadDataInfo.setDownloadSize(getFileLength(new
    // File(filename+"\\"+s)));
    // downloadDataInfo.setDownloadName(s);
    // downloadDataInfo.setDownloadUrl(P.ERP_SERVER_DATA_DOWNLOAD_URL+s);
    // downloadDataInfos.add(downloadDataInfo);
    // }
    // }
    // return downloadDataInfos;
    // }

    /**
     * 读取txt文件的内容
     *
     * @param filePath 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txtToString(String filePath, String encoding) {
        String result = "";
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if ("".equals(result) || result == null) {
                        result = lineTxt;
                    } else {
                        result = result + "\n" + lineTxt;
                    }
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读取某个文件夹下的所有文件
     */
    public static String readfile(String filepath) throws FileNotFoundException, IOException {
        try {
            File file = new File(filepath);
            if (!file.isDirectory()) {
                System.out.println("文件");
                System.out.println("path=" + file.getPath());
                System.out.println("absolutepath=" + file.getAbsolutePath());
                System.out.println("name=" + file.getName());
            } else if (file.isDirectory()) {
                System.out.println("文件夹");
                String[] filelist = file.list();
                if (filelist.length == 1) {
                    return filepath + "\\" + filelist[0];
                }
                for (int i = 0; i < filelist.length; i++) {
                    File readfile = new File(filepath + "\\" + filelist[i]);
                    if (!readfile.isDirectory()) {
                        System.out.println("path=" + readfile.getPath());
                        System.out.println("absolutepath=" + readfile.getAbsolutePath());
                        System.out.println("name=" + readfile.getName());
                    } else if (readfile.isDirectory()) {
                        readfile(filepath + "\\" + filelist[i]);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println("readfile()   Exception:" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除文件夹里所有文件
     *
     * @param path 文件夹路径
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        try {
            File file = new File(path);
            if (!file.exists()) {
                return flag;
            }
            if (!file.isDirectory()) {
                return flag;
            }
            String[] tempList = file.list();
            File temp = null;
            for (int i = 0; i < tempList.length; i++) {
                if (path.endsWith(File.separator)) {
                    temp = new File(path + tempList[i]);
                } else {
                    temp = new File(path + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
                if (temp.isDirectory()) {
                    delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                    delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除file中除文件名为filename之外的所有文件或文件夹
     *
     * @param file
     * @param fileName
     * @throws IOException 删除文件夹下的文件成功率大于直接删除文件的成功率
     */
    public static void deleteFile(File file, String fileName) throws IOException {
        File[] files = file.listFiles();
        if (files != null) {//如果包含文件进行删除操作
            for (int i = 0; i < files.length; i++) {
                if (files[i].getName().equals(fileName)) {
                    continue;
                } else {
                    if (files[i].isFile()) {
                        //删除子文件
                        files[i].delete();
                    } else if (files[i].isDirectory()) {
                        //通过递归的方法找到子目录的文件
                        deleteFile(files[i], "");
                    }
                    files[i].delete();//删除子目录
                }
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean writeTxtFile(String content, String fileName, String encoding) throws Exception {
        RandomAccessFile raf = null;
        boolean flag = false;
        FileOutputStream fos = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();// 创建目录
                }
                file.createNewFile();// 创建文件
            }
            fos = new FileOutputStream(fileName);
            fos.write(content.getBytes(encoding));
            fos.close();
            // mm=new RandomAccessFile(fileName,"rw");
            // mm.writeBytes(content);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raf != null) {
                raf.close();
            }
        }
        return flag;
    }

    /**
     * 移动单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/
     */
    public static void moveFile(String oldPath, String newPath) {
        try {
            File oldFile = new File(oldPath);
            if (!oldFile.exists()) {
                System.out.println("原文件不存在");
                return;
            }
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            boolean success = oldFile.renameTo(new File(newFile, oldFile.getName()));
            if (success) {
                oldFile.delete();
                System.out.println("移动文件：" + oldPath + "到" + newPath + "成功");
            } else {
                System.out.println("移动文件：" + oldPath + "到" + newPath + "失败");
            }
        } catch (Exception e) {
            System.out.println("移动单个文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }
                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }
    }

    /***
     * 删除多余文件夹(最多5个)
     *
     * @param backupFile
     */
    public static void moreDeleteFile(String backupFile) {
        File file = new File(backupFile);
        if (file.exists() && file.list() != null && file.list().length >= 5) {
            String[] filelist = file.list();
            String tempName = null;
            for (int i = 0; i < filelist.length - 4; i++) {
                if (backupFile.endsWith(File.separator)) {
                    tempName = backupFile + filelist[i];
                } else {
                    tempName = backupFile + File.separator + filelist[i];
                }
                File tempFile = new File(tempName);
                if (tempFile.isDirectory()) {
                    delFolder(tempName);
                    // tempFile.delete();
                } else {
                    tempFile.delete();
                }
            }
        }
    }

    /**
     * 获取txt保存路径
     */
    private static String getVoiceFile(String voiceFileId, String path) {
        return path + File.separator + voiceFileId + ".mp3";
    }

    /**
     * 语音字节流转文件流
     *
     * @param voiceFile
     */
   /* public static void byteToVoiceFile(String path, VoiceFileEntity voiceFile) {
        try {
            byte[] data = voiceFile.getVoiceFileData();
            File file = new File(getVoiceFile(voiceFile.getId(), path));
            if (file.exists()) file.delete();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data, 0, data.length);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    /**
     * 获得指定文件的byte数组
     */
    public static byte[] FileToBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 语音字节流转文件流
     */
    public static void byteToFile(byte[] data, String path) {
        try {
            File file = new File(path);
            if (file.exists()) file.delete();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(data, 0, data.length);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件转成字节数组
     *
     * @param path
     * @throws IOException
     */
    public static byte[] readVoiceFileToBytes(String path) throws IOException {
        byte[] b = null;
        InputStream is = null;
        File f = new File(path);
        try {
            is = new FileInputStream(f);
            b = new byte[(int) f.length()];
            is.read(b);
        } finally {
            if (is != null) is.close();
        }
        return b;
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) { // 删除子文件
                flag = deleteFile2(files[i].getAbsolutePath());
                if (!flag) break;
            } else if (files[i].isDirectory()) { // 删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) {
            System.out.println("删除目录失败！");
            return false;
        }
        if (dirFile.delete()) { // 删除当前目录
            System.out.println("删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile2(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

    /**
     * 读取assets中的文件 流程
     * readAssetsFile("json/xx.json", this);
     *
     * @param fileName 文件名
     * @param context  context
     * @return 读取的内容
     */
    public static String readAssetsFile(String fileName, Context context) {
        // 输入流对象
        InputStream inputStream;
        // 缓存流对象
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            // getAssets方法返回通过输入流对象
            inputStream = context.getAssets().open(fileName);
            // InputStreamReader 实现字节流到字符流的转换
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
            }
        }
        return stringBuilder.toString();
    }
}
